/*
 * @Description:
 * @Version: 2.0
 * @Author: Xing
 * @Date: 2021-02-06 15:25:50
 * @LastEditors: Xing
 * @LastEditTime: 2021-02-06 15:38:10
 */
import { ref, toRefs, onMounted, onUnmounted, reactive } from 'vue';
interface ZuoBiao {
  x: number;
  y: number;
}
function useMousePosition() {
  // ref写法 start
  // const x = ref(0);
  // const y = ref(0);
  // const updateMouse = (e: MouseEvent) => {
  //   x.value = e.pageX;
  //   y.value = e.pageY;
  // };
  // onMounted(() => {
  //   document.addEventListener('click', updateMouse);
  // });
  // onUnmounted(() => {
  //   document.removeEventListener('click', updateMouse);
  // });
  // return { x, y };
  // ref写法 end

  // reactive写法 start
  const data: ZuoBiao = reactive({
    x: 0,
    y: 0,
  });
  const updateMouse = (e: MouseEvent) => {
    data.x = e.pageX;
    data.y = e.pageY;
  };
  const refData = toRefs(data);
  onMounted(() => {
    document.addEventListener('click', updateMouse);
  });
  onUnmounted(() => {
    document.removeEventListener('click', updateMouse);
  });
  return { ...refData };
  // reactive写法 end
}

export default useMousePosition;
